// 获取当前窗口对象
const win = nw.Window.get();

// 创建右键菜单
const menu = new nw.Menu();

// 添加用VSCode打开菜单项
menu.append(new nw.MenuItem({
  label: "打开VSCode",
  click: function() {
    const folderItem = document.querySelector('.folder-item.active');
    if (folderItem) {
      openWithVSCode(folderItem.dataset.path);
    }
  }
}));

// 添加用IDEA打开菜单项
menu.append(new nw.MenuItem({
  label: "打开IDEA",
  click: function() {
    const folderItem = document.querySelector('.folder-item.active');
    if (folderItem) {
      openWithIDEA(folderItem.dataset.path);
    }
  }
}));

// 添加删除菜单项
menu.append(new nw.MenuItem({
  label: "删除",
  click: function() {
    const folderItem = document.querySelector('.folder-item.active');
    if (folderItem) {
      const path = folderItem.dataset.path;
      
      // 从本地存储中移除
      const savedFolders = JSON.parse(localStorage.getItem('savedFolders') || '[]');
      const updatedFolders = savedFolders.filter(f => f.path !== path);
      localStorage.setItem('savedFolders', JSON.stringify(updatedFolders));
      
      // 从DOM中移除
      folderItem.remove();
    }
  }
}));

// 添加重命名菜单项
menu.append(new nw.MenuItem({
  label: "重命名",
  click: function() {
    const folderItem = document.querySelector('.folder-item.active');
    if (folderItem) {
      const nameElement = folderItem.querySelector('.folder-name');
      const newName = prompt('输入新名称:', nameElement.textContent);
      
      if (newName && newName.trim() !== '') {
        nameElement.textContent = newName.trim();
        
        // 更新本地存储
        const path = folderItem.dataset.path;
        const savedFolders = JSON.parse(localStorage.getItem('savedFolders') || '[]');
        const folderIndex = savedFolders.findIndex(f => f.path === path);
        if (folderIndex !== -1) {
          savedFolders[folderIndex].name = newName.trim();
          localStorage.setItem('savedFolders', JSON.stringify(savedFolders));
        }
      }
    }
  }
}));

// 绑定右键菜单到文件夹项目
document.addEventListener('contextmenu', function(e) {
    console.log(e,'右击');
  // 检查是否点击在文件夹项目上
  let target = e.target;
  while (target && !target.classList.contains('folder-item')) {
    target = target.parentElement;
    if (target === document.body) {
      target = null;
      break;
    }
  }
  
  if (target && target.classList.contains('folder-item')) {
    // 阻止默认的HTML右键菜单
    e.preventDefault();
    e.stopPropagation();
    
    // 移除之前的高亮
    document.querySelectorAll('.folder-item').forEach(item => {
      item.classList.remove('active');
    });
    
    // 高亮当前项目
    target.classList.add('active');
    
    // 显示NW.js原生菜单
    menu.popup(e.x, e.y);
    return false;
  }
  
  // 阻止整个文档的默认右键菜单
  e.preventDefault();
  return false;
});